#include "stack.h"

void errif(int result,char *message)
{
    if(result)
    {
        printf("message:%s",message);
        exit(1);
    }
}

void OrderStack_create_stack(OrderStack *s)
{
    s->size=0;
    s->top=-1;
}

void OrderStack_push(OrderStack *s,int x)
{
    errif(s->size==MAXSIZE,"stack is full!");
    errif(s->top==MAXSIZE-1,"stack is full!");
    errif(!s,"stack is invalid!");
    s->data[s->top+1]=x;
    s->top++;
    s->size++;
}

void OrderStack_pop(OrderStack *s)
{
    errif(s->top==-1,"stack is empty when pop data!");
    s->top--;
    s->size--;
}

int OrderStack_top(OrderStack *s)
{
    errif(s->top==-1,"stack is empty when top data!");
    return s->data[s->top];
}

//end order stack

void SharedStack_clean_stack(SharedStack *s)
{
    errif(!s,"stack is invalid when clean shared stack!");
    s->top_one=-1;
    s->top_two=MAXSIZE;
}

void SharedStack_push_one(SharedStack *s,int x)
{
    errif(!s,"shared stack ptr is nullptr!");
    errif((s->top_one==-1 || s->top_one+1==s->top_two),"stack is full when push one!");
    s->data[++s->top_one]=x;
}

void SharedStack_push_two(SharedStack *s,int x)
{
    errif(!s,"shared stack ptr is nullptr!");
    errif((s->top_two==-1 || s->top_two-1==s->top_one),"stack is full when push two!");
    s->data[s->top_two--]=x;
}

void SharedStack_pop_one(SharedStack *s)
{
    errif(!s,"shared stack ptr is nullptr!");
    errif(s->top_one==-1,"stack is empty when pop one!");
    s->top_one--;
}

void SharedStack_pop_two(SharedStack *s)
{
    errif(!s,"shared stack ptr is nullptr!");
    errif(s->top_two==-1,"stack is empty when pop two!");
    s->top_two++;
}

int SharedStack_top_one(SharedStack *s)
{
    errif(!s,"shared stack ptr is nullptr!");
    errif(s->top_one==-1,"stack is empty when top one!");
    return s->data[s->top_one];
}

int SharedStack_top_two(SharedStack *s)
{
    errif(!s,"shared stack ptr is nullptr!");
    errif(s->top_two==-1,"stack is empty when top two!");
    return s->data[s->top_two];
}

//end shared stack

void LinkedStack_create_stack(LinkedStack *s)
{
    s=(LinkedStack*)malloc(sizeof(LinkedStack));
    s->next=NULL;
}

void LinkedStack_destroy_stack(LinkedStack *s)
{
    LinkedStack *temp=s->next;
    while(temp)
    {
        s->next=temp->next;
        free(temp);
        temp=s->next;
    }
    free(s);
    s=NULL;
}

void LinkedStack_push(LinkedStack *s,int x)
{
    errif(!s,"linked stack ptr is nullptr!");
    LinkedStack *temp=(LinkedStack*)malloc(sizeof(LinkedStack));
    temp->data=x;
    temp->next=s->next;
    s->next=temp;
}

void LinkedStack_pop(LinkedStack *s)
{
    errif(!s,"linked stack ptr is nullptr!");
    errif(!s->next,"linked stack is empty when pop!");
    LinkedStack *temp=s->next;
    s->next=temp->next;
    free(temp);
}

int LinkedStack_top(LinkedStack *s)
{
    errif(!s,"linked stack ptr is nullptr!");
    errif(!s->next,"linked stack is empty when top!");
    return s->next->data; 
}
